-- SkyStoneM
-- Create by chendh
-- 天空之城符石系统

module("SkyStoneM", package.seeall);

-- 所有的配置信息
local stoneTable = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    -- 转换下airship信息表
    local skyStone_CSV = get_sky_stone_CSV();
    local list = table.keys(skyStone_CSV);
    for i = 1, #list do
        local info = skyStone_CSV[list[i]];
        stoneTable[info.id] = info;
    end

    skyStone_CSV = {};
end

-- 模块初始化
function init()
    loadCsv();
end

-- 检索信息
function query(id, path)
    local m = stoneTable[id]

    if not m or path == "" or not path then
        return m
    end

    return m[path];
end


-- 删除战斗对象的某条符石属性
function deleteFighterProp(fighter, rule, type)
    local prop;
    local skyStoneProp = fighter.dbase:query("sky_stone_prop") or {};

    prop = skyStoneProp[rule];
    if not prop then
        return true;
    end

    if type == UNDEFINED then
        skyStoneProp[rule] = nil;
    else
        prop[type] = nil;
    end

    return true;
end

-- 获取天空战战斗对象的符石属性
function getFighterProp(fighter, rule, type)
    local skyStoneProp = fighter.dbase:query("sky_stone_prop") or {};

    if not skyStoneProp[rule] then
        return nil;
    end

    return skyStoneProp[rule][type];
end

-- 是否有符石
function hasStone(style)
    local stoneList = SkyResourceM.getResourcesByPage("stone");
    printTable(stoneList, "stoneList");
    for _, data in pairs(stoneList) do
        local tempStyle = query(data.class_id, "style");
        if tempStyle == style and data.amount > 0 then
            return true;
        end
    end
    
    return false;
end

-- 分解符石
function splitStone(id, amount)
    local split = query(id, "split");
    if not split then 
        return false;
    end
    
    if (amount > ItemM.getAmount(ME.user, id)) then
        cclog(string.format("玩家(%s/%s)尝试分解%d个%d符石，数量不足，分解失败。\n", ME.user:getName(), ME.user:getRid(), amount, id));
        return false;
    end

    -- 先扣除数量
    ItemM.costAmount(ME.user, id, amount);

    for _, bonus in pairs(split) do
        BonusM.doBonus(bonus, "split_stone");
    end

    -- 发给服务器
    Operation.cmd_split_stone(id, amount);

    return true;
end
